<?php

namespace app\admin\controller\finance;

use service\JsonService;
use app\common\model as M;

/**
 * 订单模块
 */
class Order extends \app\admin\controller\AuthController
{
	public $model = '\app\common\model\Order';

    use \traits\ShotcutControllerTrait;
	
	/**
	 * 兑换订单明细
	 */
    public function exchangeOrderInfo($order_id)
	{
		$orderBaseInfo = $this->model::getOne($order_id);
		
		if (!empty($orderBaseInfo) ) {
			$orderBaseInfo['outer'] = M\OrderOuterExchange::alias('ex')
				->field("ex.id,concat(ua.province,ua.city,ua.area,ua.address) as address_display,g.goods_name,ex.nums,ex.logistic_no")
				->join('__USER_ADDRESS__ ua' , 'ex.address_id = ua.id' , 'left')
				->join('__GOLDS_GOODS__ g' , 'ex.goods_id = g.id' , 'left')
				->where('ex.id',$orderBaseInfo['order_outer_id'])
				->find();
		}
		return JsonService::successful($orderBaseInfo);
	}
	
	/**
	 * 兑换订单发货
	 */
	public function confirmExchangeOrderFahuo()
	{
		$post = $this->request->post();
		$logistic_no = $post['logistic_no'] ?? '';
		$id = (int)$post['id'];
		
		if ( $id && $logistic_no ) {
			$res = M\OrderOuterExchange::where('id',$id)->update([
				'logistic_no' => $logistic_no,
				'status'      => M\OrderOuterExchange::TYPE_DELIVERYED
			]);
			if ( $res ) return JsonService::successful();
		}
		
		return JsonService::fail('操作失败');
	}

	/**
	 * 线路预定订单明细
	 */
    public function routeOrderInfo($order_id)
	{
		$orderBaseInfo = $this->model::getOne($order_id);

		if (!empty($orderBaseInfo) ) {
			$orderBaseInfo['outer'] = M\OrderOuterRoutes::alias('outer')
				->field("outer.id,outer.route_id,outer.sku_id,outer.date,outer.nums,outer.double_room,outer.big_room,route.route_name,sku.sku_name,ifnull(user.full_name,user.nickname) as user_fullname,user.mobile as user_mobile")
				->join('__ORDER__ o' , 'outer.id = o.order_outer_id')
				->join('__ROUTES__ route' , 'outer.route_id = route.id')
				->join('__ROUTES_SKU__ sku' , 'outer.sku_id = sku.id')
				->join('__USER__ user' , 'o.uid = user.uid')
				->where('outer.id',$orderBaseInfo['order_outer_id'])
				->find();
		}
		return JsonService::successful($orderBaseInfo);
	}

	/**
	 * 线路预定订单确认
	 * 暂不支持修改信息
	 */
	public function confirmRouteOrder()
	{
		$post = $this->request->post();
		$id = (int)$post['id'];

		if ( $id ) {
			$res = M\OrderOuterRoutes::where('id',$id)->update([
				'status'      => M\OrderOuterRoutes::TYPE_UNGO
			]);
			if ( $res ) return JsonService::successful();
		}

		return JsonService::fail('操作失败');
	}

	/**
     * 订单统计信息
     */
    public function loadOrderState()
    {
    	$orderState = [
            "totalOrderNums" => 0, // 总单数
            "avgOrderPrice"  => 0, // 客单价
            "paymentNums"    => 0, // 支付数
            "paymentAmt"     => 0, // 付款金额
            "refundNums"     => 0  // 退款数
        ];

        $orderState['totalOrderNums'] = $this->model::count();
        $orderState['paymentAmt'] = $this->model::where('pay_status',1)->sum('order_amt');
        $orderState['paymentNums'] = $this->model::where('pay_status',1)->count();
        $orderState['avgOrderPrice'] = $orderState['paymentNums'] > 0 ? bcdiv($orderState['paymentAmt'], $orderState['paymentNums'],2) : 0;
        $orderState['refundNums'] = $this->model::where('status',3)->count();
        return JsonService::successful($orderState);
    }

    /**
     * 订单图标
     */ 
    public function orderChart( $chartType = 'day' )
    {
    	$option = [
    		'xAxis' => [
    			'type'        => 'category',
                'boundaryGap' => false,
                'data'        => []
    		],
    		'series' => [
    			[
                    'name' => '订单数',
                    'type' => 'line',
                    'stack' => 'Total',
                    'data' => []
                ],
                [
                    'name' => '订单金额',
                    'type' => 'line',
                    'stack' => 'Total',
                    'data' => []
                ]
    		]
    	];

    	$oderNums = $orderAmt = [];
    	if ( $chartType == 'day' ) {
    		for ($i=0; $i < 24; $i++) {
    			if ( $i < 10 ) $i = '0' . $i;

    			$oderNums[$i] = $orderAmt[$i] = 0;
    		}
    		
    		$todayOrders = $this->model::field('order_amt,create_time')->where('create_time','BETWEEN' , [date('Y-m-d 00:00:00'),date('Y-m-d 23:59:59')])->select();
    		## 按小时切割成24份
    		foreach ( $todayOrders as $order ) {
    			$hour = date('H' , strtotime($order['create_time']));

    			if ( isset($oderNums[$hour]) ) {
    				$oderNums[$hour]++;
    			}

    			if ( isset($orderAmt[$hour]) ) {
    				$orderAmt[$hour] += $order['order_amt'];
    			}
    		}
    	}

    	if ( $chartType == 'month' ) {
    		$firstOfMonth = date('Y-m-01');
    		$lastOfMonth  = date('Y-m-d' , strtotime("last day of this month"));

    		$day = $firstOfMonth;
    		while ( strtotime($day) <= strtotime($lastOfMonth) ) {
    			$dayText = date('m-d' , strtotime($day));
    			$oderNums[$dayText] = $orderAmt[$dayText] = 0;

    			$day = date('Y-m-d',strtotime($day . ' +1 days'));
    		}
    		
    		$monthOrders = $this->model::field('order_amt,create_time')->where('create_time','BETWEEN',[$firstOfMonth.' 00:00:00',$lastOfMonth.' 23:59:59'])->select();
    		## 按小时切割成24份
    		foreach ( $monthOrders as $order ) {
    			$dayText = date('m-d' , strtotime($order['create_time']));

    			if ( isset($oderNums[$dayText]) ) {
    				$oderNums[$dayText]++;
    			}

    			if ( isset($orderAmt[$dayText]) ) {
    				$orderAmt[$dayText] += $order['order_amt'];
    			}
    		}
    	}

    	$option['xAxis']['data'] = array_keys($oderNums);
    	$option['series'][0]['data']  = array_values($oderNums);
    	$option['series'][1]['data']  = array_values($orderAmt);

    	return JsonService::successful($option);
    }

    /**
     * 获取订单待结算尾款情况
     * @Author   FW
     * @DateTime 2024-04-18
     * @Email    123763712@qq.com
     * @return   [type]           [description]
     */
    public function finalInfo($order_id)
    {
    	$orderBaseInfo = $this->model::getOne($order_id);

		if (!empty($orderBaseInfo) ) {
			if ( $orderBaseInfo['use_deposit'] != 1 ) return JsonService::fail('该订单未使用定金');

			$depositOrder = M\OrderSubs::where('order_id',$order_id)->where('order_type',1)->find();
			if ( $depositOrder->pay_status != M\Order::STATUS_PAID ) return JsonService::fail('定金支付异常，暂不可确认尾款');

			$finalOrder = M\OrderSubs::where('order_id',$order_id)->where('order_type',2)->find();
			if ( $finalOrder->pay_status == M\Order::STATUS_PAID ) return JsonService::fail('尾款已支付！');

			$dataInfo = [
				'order_id'  => $order_id,
				'order_amt' => $orderBaseInfo['order_amt'],
				'deposit'=> [
					'id'           => $depositOrder->id,
					'order_amt'    => $depositOrder->order_amt,
					'out_trade_no' => $depositOrder->out_trade_no
				],
				'final' => [
					'id'           => $finalOrder->id,
					'order_amt'    => $finalOrder->order_amt,
					'out_trade_no' => $finalOrder->out_trade_no
				],
			];
			return JsonService::successful($dataInfo);
		}

		return JsonService::fail('操作失败');
    }

    /**
     * 确认订单已收尾款
     * @Author   FW
     * @DateTime 2024-04-18
     * @Email    123763712@qq.com
     * @return   [type]           [description]
     */
    public function confirmFinalInfo()
    {
    	$post = $this->request->post();
		$final = $post['final'] ?? [];

		$final_amt = $final['order_amt'] ?? 0;
		$out_trade_no = $final['out_trade_no'] ?? 0;
		$final_id = $final['id'] ?? 0;

		if ( !$final_id || !$out_trade_no || !$final_amt ) return JsonService::fail('操作失败[1001]');
		$finalOrder = M\OrderSubs::where('id',$final_id)->find();

		if ( empty($finalOrder) ) return JsonService::fail('操作失败[1002]');

		M\OrderSubs::startTrans();
		try {
			$order = M\Order::where('id',$finalOrder->order_id)->find();

			$remark = sprintf('【%s】确认订单尾款', $this->adminInfo['real_name']);
			## 修改了尾款金额，记录日志
			if ( $order->final_amt != $final_amt ) {
				$remark .= sprintf('。修改了尾款数额【%.2f修改为%.2f】',$order->final_amt,$final_amt);
				$order->final_amt = $final_amt;
			}

			$res = $order->save();
			if ( $res === false ) exception('更新订单失败【2001】');

			$finalOrder->out_trade_no = $out_trade_no;
			$res = $finalOrder->save();
			if ( $res === false ) exception('更新订单失败【2002】');

			M\OrderLogs::create([
				'order_id'    => $order->id,
				'uid'         => 0,
				'status'      => $order->status,
				'create_time' => date('Y-m-d H:i:s'),
				'remark'      => $remark
			]);

			$res = M\Order::paySuccess($finalOrder->order_no , $out_trade_no);
			if ( $res === false ) exception('更新订单失败【2003】');

			M\OrderSubs::commitTrans();
			return JsonService::successful();
		} catch ( \Exception $e ) {
			M\OrderSubs::rollbackTrans();
			return JsonService::fail($e->getMessage());
		}
		M\OrderSubs::rollbackTrans();
		return JsonService::fail('操作失败');
    }
} //Class End